﻿@using OBUCare.Web.Infrastructure;
@using OBUCare.Core.Models;
@using OBUCare.Core.BL
@using OBUCare.Core.DataAccess;
@using OBUCare.Core.Common;
@{
    ViewBag.Title = "List";

    ObuDropDownListHlper ddlHelper = new ObuDropDownListHlper();
}
<h2 style="text-align: center;">
    元器件型号配置</h2>
<div>
    <table style="width: 100%">
        <tr>
            <td style="width: 10%; text-align: right; height: 40px;">
                元器件：
            </td>
            <td style="width: 20%; text-align: left">
                @Html.Telerik().DropDownList().Name("PartTypes").BindTo(ddlHelper.GetPartTypes(UIConstants.AllItems, true, new KeyValuePair<string, string>(UIConstants.AllItemsValue.ToString(), UIConstants.AllItems))).Value(UIConstants.AllItemsValue.ToString()).ClientEvents(events => events.OnChange("onMasterDDLChange"))
            </td>
            <td style="width: 10%; text-align: right; height: 40px;">
                厂商：
            </td>
            <td style="width: 20%; text-align: left">
                @Html.Telerik().DropDownList().Name("Supplier").BindTo(ddlHelper.GetSuppliers(UIConstants.AllItems, false, new KeyValuePair<string, string>(UIConstants.AllItemsValue.ToString(), UIConstants.AllItems))).ClientEvents(events => events.OnChange("onMasterDDLChange"))
            </td>
            <td style="width: 10%; text-align: right; height: 40px;">
                状态：
            </td>
            <td style="width: 20%; text-align: left">
                @Html.Telerik().DropDownList().Name("Status").BindTo(ddlHelper.GetPartsSpecStatus(DictTypeStatus.Normal.ToInt().ToText(), false, new KeyValuePair<string, string>(UIConstants.AllItemsValue.ToString(), UIConstants.AllItems))).ClientEvents(events => events.OnChange("onMasterDDLChange"))
            </td>
            <td style="width: 10%; text-align: left">
                <input type="button" value="增加" onclick="OpenAddSpec('','');" />
            </td>
        </tr>
    </table>
</div>
<div>
    @{Html.Telerik().Grid<PARTS_SPECS>()
          .Name("MasterGrid")
          .DataKeys(keys => keys
              .Add(t => t.ID)
              .RouteKey("ID"))
          .DataBinding(dataBinding => dataBinding.Ajax()
                .Select("List", "PartsSpec", new { supplier = UIConstants.AllItemsValue, status = UIConstants.AllItemsValue })
                .Update("SaveSpec", "PartsSpec")
                .Delete("DeleteSpec", "PartsSpec"))
          .Columns(columns =>
          {
              columns.Bound(t => t.PARTS_NAME).ReadOnly();
              columns.Bound(t => t.SUPPLIER_NAME).ReadOnly();
              columns.Bound(t => t.SPEC_NAME);
              columns.Bound(t => t.StatusText).ReadOnly();
              columns.Bound(t => t.STATUS).Visible(false);
              columns.Command(commands =>
              {
                  commands.Edit()
                      .ButtonType(CommonStyleForUI.Grid_ButtuonType).Text("编辑").CancelText("取消").UpdateText("更新");
              }).Width(100).Title("编辑");
              columns.Command(commands =>
              {
                  commands.Delete()
                      .ButtonType(CommonStyleForUI.Grid_ButtuonType).Text("删除");
              }).Width(100).Title("删除");
          })
            .ClientEvents(events => events
                .OnError("onError")
                .OnDataBound("onDataBound")
                .OnDataBinding("onMasterDataBinding")
                .OnDelete("MasterGrid_onDelete")
                .OnSave("MasterGrid_onSave")
                .OnRowDataBound("onMasterRowDataBound")
                .OnDetailViewExpand("onMasterDetailViewExpand")
                )
            .Editable(editing => editing.Mode(GridEditMode.InLine))
            .Pageable(paging => paging.Style(CommonStyleForUI.Grid_PageStyle).Position(CommonStyleForUI.Grid_PagePosition).PageTo(CommonStyleForUI.Grid_CurrentPage).PageSize(CommonStyleForUI.Grid_PageSize))
            .KeyboardNavigation()
            .Sortable()
          //.Filterable()
            .Selectable()
          //.HtmlAttributes(new { style = "width:80%;" })
            .DetailView(details => details
            .ClientTemplate(Html.Telerik().Grid<PARTS_SPECS_DETAIL>()
                .Name("Master_<#= ID #>")
                .Columns(columns =>
                {
                    columns.Bound(d => d.START_NO).ReadOnly();
                    columns.Bound(d => d.END_NO).ReadOnly();
                    //columns.Bound(d => d.CONTRACT_DETAIL_ID).ReadOnly();
                    columns.Bound(d => d.STATUS).Visible(false);
                    columns.Command(commands =>
                    {
                        commands.Custom("Update").ButtonType(CommonStyleForUI.Grid_ButtuonType)
                            .Text("更新").Action("UpdateDetails", "PartsSpec").Ajax(true).DataRouteValues(route => route.Add(o => o.ID).RouteKey("id"));
                    }).Width(100).Title("更新");
                    columns.Command(commands =>
                    {
                        commands.Delete().ButtonType(CommonStyleForUI.Grid_ButtuonType).Text("删除");
                    }).Width(100).Title("删除");
                })
                .ToolBar(toolBar => toolBar.Template
                    (
        @<text>
        <table id="tblToolBar">
            <tr>
                <td style="text-align: left">
                    @item.CustomCommandToolBarButton("btnGvDetialOpenAddSpec", "增加", "javascript:OpenAddSpec('<#= SUPPLIER_ID #>','<#= ID #>');", GridButtonType.Text, new { @id = "btnGvDetialOpenAddSpec", @value = "<#= ID #>", @style = "width:100px;font-size:14px;" }, null)
                </td>
            </tr>
        </table>
        </text>
)
                )
                .DataBinding(dataBinding => dataBinding.Ajax()
                    .Select("ListDetails", "PartsSpec", new { masterID = "<#= ID #>" })
                    //.Update("SaveDetails", "PartsSpec", new { masterID = "<#= ID #>" })
                    .Delete("DeleteSpecDetails", "PartsSpec", new { masterID = "<#= ID #>" }))
                .DataKeys(keys => keys
                    .Add(d => d.ID)
                        .RouteKey("detailID"))
                .ClientEvents(events => events
                    .OnError("onError")
                    .OnDataBound("onDataBoundDetails")
                    .OnComplete("onDetailsComplete")
                    .OnRowDataBound("onDetailsRowDataBound")
                    )
                .Pageable(paging => paging.Style(CommonStyleForUI.Grid_PageStyle).Position(CommonStyleForUI.Grid_PagePosition).PageTo(CommonStyleForUI.Grid_CurrentPage).PageSize(CommonStyleForUI.Grid_PageSize))
                .KeyboardNavigation()
                .Editable(editing => editing.Mode(GridEditMode.PopUp))
                .Sortable()
                //.Filterable()
                .ToHtmlString()))
            .Render();  
    }
</div>
<div>
    @(Html.Telerik().Window()
    .Name("Window")
            //.LoadContentFrom("addspec", "PartsSpec")
    .Buttons(buttons => buttons.Maximize().Close())
    .Width(900)
    .Draggable(true)
    .Title("元器件型号号段配置")
    .Visible(false)
    .Content
        (
            @<text>
    @Html.Partial("AddSpec")
    </text>
        )
    )
    <input type="hidden" id="hidCurrentSpecID" />
</div>
<script type="text/javascript">


    //打开添加型号页
    function OpenAddSpec(supplier, specID) {

        //$("#hidCurrentSpecID").val(specID);
        $("#mtxtSpecName").val("");

        //厂商编号
        if (supplier.StringIsNullOrEmpty())
            supplier = $("#Supplier").data("tDropDownList").value();

        $("#mSupplier").data("tDropDownList").value(supplier);
        SupplierChanged(function () {

            if (!specID.StringIsNullOrEmpty())
                $("#mSpecName").data("tDropDownList").value(specID);
            onSpecNameChange();
        });



        var window = $("#Window").data("tWindow");
        window.center();
        window.restore();
        window.open();
    }


    function onError(e) {

        e.preventDefault();
        if (e.XMLHttpRequest.status == "505")
            alert("系统字段不允许删除");
        else if (e.XMLHttpRequest.status == "500")
            alert("该型号已引用，不允许编辑");
        else if (e.XMLHttpRequest.status == "501")
            alert("该型号已作废，不允许编辑");
        else if (e.XMLHttpRequest.status == "502")
            alert("该型号名称已存在，不允许重复");
        else if (e.XMLHttpRequest.status == "503")
            alert("该型号已引用，不允许删除");
        else if (e.XMLHttpRequest.status == "506")
            alert("系统表不允许删除");
        else
            alert(e.XMLHttpRequest.getResponseHeader("message"));
    }

    function onDataBound() {

        replaceDeleteConfirmation(this, "MasterGrid");
    }

    function onMasterDataBinding(e) {
        var partsType = $("#PartTypes").data("tDropDownList").value();
        var s = $("#Supplier").data("tDropDownList").value();
        var status = $("#Status").data("tDropDownList").value();
        var grid = $('#MasterGrid').data('tGrid')
        index = (grid.currentPage - 1) * grid.pageSize;
        e.data = {
            // the key ("category") specifies the variable name of the action method which will contain the specified value
            supplier: s,
            status: status,
            partsType:partsType
        };
    }

    function onMasterRowDataBound(e) {

        //the DOM element (<tr>) representing the row which is being databound
        var row = e.row;
        //the data item - JavaScript object.
        var dataItem = e.dataItem;

        var Normal = parseInt('@DictTypeStatus.Normal.ToInt()');
        if (dataItem.STATUS != Normal) {
            row.cells[5].innerHTML = "";
            row.cells[6].innerHTML = "";
        }
    }

    function onDataBoundDetails() {
        //$(this).find(".t-grid-add").first().text("添加").prepend("<span class='t-icon t-add'>");
        replaceDeleteConfirmation(this, "Order");
    }



    function replaceDeleteConfirmation(item, itemType) {
        var grid = $(item).data('tGrid');
        $(item).find('.t-grid-delete').click(function () {
            //grid.localization.deleteConfirmation = "你确定要删除此条记录： " + itemType + "?";
            grid.localization.deleteConfirmation = "你确定要删除此条记录? ";
        });
    }

    //号段详情列表，请求结束后的事件
    function onDetailsComplete(e) {
        //debugger;
        //当点击更新号段后
        if (e.name == "Update") {
            var result = e.response;
            if (result.success) {
                var grid = $(this).data("tGrid");
                grid.ajaxRequest();
                alert("更新成功");
            }
            else
                alert("更新失败:" + result.message);
        }
    }

    function onMasterDDLChange(e) {
        var grid = $('#MasterGrid').data('tGrid')
        grid.rebind();
    }

    function MasterGrid_onDelete(e) {
        //debugger;
        // Send additional values
        AddAdditionalValues(e);
    }

    function MasterGrid_onSave(e) {

        AddAdditionalValues(e);
    }

    //在删除，保存事件时，添加查询条件
    function AddAdditionalValues(e) {
        var supplier = $("#Supplier").data("tDropDownList").value();
        var status = $("#Status").data("tDropDownList").value();
        var partsType = $("#PartTypes").data("tDropDownList").value();
        e.values.Qsupplier = supplier;
        e.values.Qstatus = status;
        e.values.QpartsType = partsType;
    }

    //展开详情列表时
    function onMasterDetailViewExpand(e) {

        var masterRow = $(e.masterRow);

        if (masterRow.find("a:contains(删除)").length <= 0) {
            var detailRow = $(e.detailRow);
            detailRow.find('#btnGvDetialOpenAddSpec').attr("style", "display:none;");
        }
    }

    function onDetailsRowDataBound(e) {
        //the DOM element (<tr>) representing the row which is being databound
        var row = e.row;
        //the data item - JavaScript object.
        var dataItem = e.dataItem;

        var Normal = parseInt('@DictTypeStatus.Normal.ToInt()');
        if (dataItem.STATUS != Normal) {
            row.cells[2].innerHTML = "";
            row.cells[3].innerHTML = "";
        }
    }
</script>
@{
    ddlHelper.Dispose();    
}
